package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import net.sf.json.JSONArray
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONException

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.text.SimpleDateFormat

/**
 * 计划停水*/
class apiWaterOffSync implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiWaterOffSync.class)

    @Override
    String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        //封装返回报文对象
        JSONObject resultJson = new JSONObject();
        //获取开始时间戳
        long startTime = System.currentTimeMillis();

        String jsonBody = null
        JSONObject json = null
        //获取通知返回结果
        List list = null
        try {
            //获取rec_guid唯一id
            String recGuid = UUID.randomUUID().toString().toUpperCase();
            //获取入参报文
            jsonBody = Util.getRequestBody(request, 'utf-8')
            log.debug("入参报文：" + jsonBody)
            JSONObject jsonObject = JSONObject.fromObject(jsonBody);

            String apiid = "waterOff";
            String apikey = "55bd38420d354822bdb789284fac4ab3";
            String timestamp = jsonObject.getString("timestamp");//时间戳
            String sign = jsonObject.getString("sign");//密钥

            log.debug("解析信息-" + " timestamp: " + timestamp + " sign: " + sign);

            String signBefore = "apiid=" + apiid + "&apikey=" + apikey + "&timestamp=" + timestamp;
            String signAfter = "";
            try {
                signAfter = Util.getMD5Str(signBefore);
                log.debug("签名MD5:" + signAfter);
            } catch (Exception e) {
                signAfter = "";
                log.warn("签名异常");
            }
            log.debug("签名信息:" + signAfter);

            //KHUtil.isNull(signAfter) || signAfter != sign
            if (1!=1) {
                resultJson.put("code", -3);
                resultJson.put("msg", "签名信息错误");
            } else {
                //停水批次编号(唯一)
                String waterOffSmsGuid = jsonObject.getString("wateroffsmsguid");
                //sync_type 类型 add新增，update更新，change改期 ，delay延期，cancel取消
                String syncType = jsonObject.getString("sync_type");
                //原停水编号
                String waterOffOldSmsGuid = jsonObject.getString("wateroffoldsmsguid");
                //类型
                String waterOffChangeType = jsonObject.getString("wateroffchangetype");
                //原因
                String waterOffChangeReason = jsonObject.getString("wateroffchangereason");
                //停水批次名称
                String waterOffSmsName = jsonObject.getString("wateroffsmsname");
                //停水原因
                String cutOffWater = jsonObject.getString("cutoffwater");
                //关阀时间
                String waterOffTime = jsonObject.getString("waterofftime");
                //恢复通水时间
                String waterOnTime = jsonObject.getString("waterontime");
                //停水短信内容对象
                String smsData = jsonObject.getString("sms_data");
                log.debug("短信内容对象:" + smsData)
                //解析停水短信内容json对象报文
                JSONObject smsObject = JSONObject.fromObject(smsData);
                //停水短信内容文本
                String content = smsObject.getString("content");
                JSONArray jsonArray = JSONArray.fromObject(smsObject.getString("data"));
                Integer listNum = jsonArray.size();
                log.debug("数量:" + listNum)
                //ivr_data 语音播报内容
                String ivrData = jsonObject.getString("ivr_data");
                log.debug("语音播报内容对象:" + ivrData)
                //解析停水ivr json报文数据
                JSONObject ivrObject = JSONObject.fromObject(ivrData);
                //语音播报类型
                String typeId = ivrObject.getString("typeid");
                //ivr播报内容 如果第二次调用播报内容为空则为取消对应批次的播报
                String ivrContent = ivrObject.getString("content");
                //现场停水负责人名称
                String person = ivrObject.getString("person");
                //现场停水负责人电话
                String phone = ivrObject.getString("phone");
                //获取传真数据
                String faxData = jsonObject.getString("fax_data");
                log.debug("传真数据对象:" + faxData)
                JSONObject faxObject = JSONObject.fromObject(faxData);
                //解析传真地址json报文
                String faxUrl = faxObject.getString("data1");
                JSONArray faxArray = JSONArray.fromObject(faxUrl);
                //获取传真通知单位json报文
                String company = faxObject.getString("data2");
                JSONArray companyArray = JSONArray.fromObject(company);
                /*
                 expand 综调其他业务信息
                 */
                String expand = jsonObject.getString("expand");
                JSONObject prePer = JSONObject.fromObject(expand);
                String sn = prePer.getString("sn");
                String agent = prePer.getString("agent");
                String original_sn = prePer.getString("original_sn");
                String wygd = prePer.getString("wygd");
                String fb = prePer.getString("fb");
                String bm = prePer.getString("bm");
                String reason = prePer.getString("reason");
                String address = prePer.getString("address");
                String tsyh = prePer.getString("tsyh");
                String scope = prePer.getString("scope");
                String stop_type = prePer.getString("stop_type");
                String sub_company = prePer.getString("sub_company");
                String dwtsyhsl = prePer.getString("dwtsyhsl");
                String main_diameter = prePer.getString("main_diameter");
                String const_diameter = prePer.getString("const_diameter");
                String project = prePer.getString("project");
                String delay_time = prePer.getString("delay_time");
                String delay_reason = prePer.getString("delay_reason");
                String emergency_level = prePer.getString("emergency_level");
                String emergency_case = prePer.getString("emergency_case");
                String bt = prePer.getString("bt");
                String tsycyy = prePer.getString("tsycyy");
                String tsycsj = prePer.getString("tsycsj");
                String yxsyyh = prePer.getString("yxsyyh");
                String tzycsm = prePer.getString("tzycsm");
                String tzyscj = prePer.getString("tzyscj");
                String tztsqy = prePer.getString("tztsqy");
                String ycwxts = prePer.getString("ycwxts");
                String ycyybb = prePer.getString("ycyybb");
                String ycdxtz = prePer.getString("ycdxtz");
                String faxorg = prePer.getString("faxorg");
                String faxdoc = prePer.getString("faxdoc");
                String mailorg = prePer.getString("mailorg");
                String maildoc = prePer.getString("maildoc");
                String attachemenyt = prePer.getString("attachemenyt");
                String stop_time = prePer.getString("stop_time");
                if (KHUtil.isNull("sync_type")) {
                    resultJson.put("code", "-2");
                    resultJson.put("msg", "调用参数非空校验异常停水类型必填字段;,调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                } else {
                    // 拼接获取各类调用必填参数信息
                    String isCheckNull = KHUtil.isNullMSG("wateroffsmsguid", waterOffSmsGuid) + KHUtil.isNullMSG("wateroffsmsname", waterOffSmsName) + KHUtil.isNullMSG("cutoffwater", cutOffWater) + KHUtil.isNullMSG("waterofftime", waterOffTime) + KHUtil.isNullMSG("waterontime", waterOnTime) + KHUtil.isNullMSG("sms_data", smsData) + KHUtil.isNullMSG("content",content) + KHUtil.isNullMSG("ivr_data", ivrData) + KHUtil.isNullMSG("typeid",typeId) + KHUtil.isNullMSG("content",ivrContent) + KHUtil.isNullMSG("person",person) + KHUtil.isNullMSG("phone",phone) + KHUtil.isNullMSG("expand", expand);
                    if (syncType.equals("change") && syncType.equals("delay") && syncType.equals("cancel")) {
                        isCheckNull += KHUtil.isNullMSG("waterOffChangeType", waterOffChangeType) + KHUtil.isNullMSG("waterOffChangeReason", waterOffChangeReason)
                    }
                    // 如果必填参数信息不为空说明有为空参数
                    if (!KHUtil.isNull(isCheckNull)) {
                        resultJson.put("code", "-2");
                        resultJson.put("msg", "调用参数非空校验异常:" + isCheckNull + "，调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime));
                    } else {
                        //插入主表
                        String doMainSql = '''INSERT INTO swg_wateroffsync (
                                                rec_guid,
                                                wateroffsmsguid,
                                                wateroffoldsmsguid,
                                                wateroffchangetype,
                                                wateroffchangereason,
                                                wateroffsmsname,
                                                cutoffwater,
                                                waterofftime,
                                                waterontime,
                                                sync_type,
                                                sn,
                                                agent,
                                                original_sn,
                                                wygd,
                                                fb,
                                                bm,
                                                reason,
                                                address,
                                                tsyh,
                                                scope,
                                                stop_type,
                                                sub_company,
                                                dwtsyhsl,
                                                main_diameter,
                                                const_diameter,
                                                project,
                                                delay_time,
                                                delay_reason,
                                                emergency_level,
                                                emergency_case,
                                                bt,
                                                tsycyy,
                                                tsycsj,
                                                yxsyyh,
                                                tzycsm,
                                                tzyscj,
                                                tztsqy,
                                                ycwxts,
                                                ycyybb,
                                                ycdxtz,
                                                faxorg,
                                                faxdoc,
                                                mailorg,
                                                maildoc,
                                                attachemenyt,
                                                stop_time,
												ivrContent,
												listNum,
												sms_guid,
												createddate
                                                )
                                                VALUES
                                                (
                                                \'''' + recGuid + '''\',
                                                \'''' + waterOffSmsGuid + '''\',
                                                \'''' + waterOffOldSmsGuid + '''\',
                                                \'''' + waterOffChangeType + '''\',
												 \'''' + waterOffChangeReason + '''\',
                                                \'''' + waterOffSmsName + '''\',
                                                \'''' + cutOffWater + '''\',
                                                \'''' + waterOffTime + '''\',
                                                \'''' + waterOnTime + '''\',
                                                \'''' + syncType + '''\',
                                                \'''' + sn + '''\',
                                                \'''' + agent + '''\',
                                                \'''' + original_sn + '''\',
                                                \'''' + wygd + '''\',
                                                \'''' + fb + '''\',
                                                \'''' + bm + '''\',
                                                \'''' + reason + '''\',
                                                \'''' + address + '''\',
                                                \'''' + tsyh + '''\',
                                                \'''' + scope + '''\',
                                                \'''' + stop_type + '''\',
                                                \'''' + sub_company + '''\',
                                                \'''' + dwtsyhsl + '''\',
                                                \'''' + main_diameter + '''\',
                                                \'''' + const_diameter + '''\',
                                                \'''' + project + '''\',
                                                \'''' + delay_time + '''\',
                                                \'''' + delay_reason + '''\',
                                                \'''' + emergency_level + '''\',
                                                \'''' + emergency_case + '''\',
                                                \'''' + bt + '''\',
                                                \'''' + tsycyy + '''\',
                                                \'''' + tsycsj + '''\',
                                                \'''' + yxsyyh + '''\',
                                                \'''' + tzycsm + '''\',
                                                \'''' + tzyscj + '''\',
                                                \'''' + tztsqy + '''\',
                                                \'''' + ycwxts + '''\',
                                                \'''' + ycyybb + '''\',
                                                \'''' + ycdxtz + '''\',
                                                \'''' + faxorg + '''\',
                                                \'''' + faxdoc + '''\',
                                                \'''' + mailorg + '''\',
                                                \'''' + maildoc + '''\',
                                                \'''' + attachemenyt + '''\',
                                                \'''' + stop_time + '''\',
												\'''' + ivrContent + '''\',
												\'''' + listNum + '''\',
												\'''' + recGuid + '''\',
												getdate()
                                                )''';
                        log.debug("插入主表SQL:" + doMainSql.toString());
                        int doMainSqlRow = eliteBean.update(doMainSql, "dataSource");
                        log.debug("存入swg_wateroffsync主表数据量为：" + doMainSqlRow);
                    }
                }
                for (int j = 0; j < faxArray.size(); j++) {
                    //传真文件地址对象
                    JSONObject urlObject = faxArray.getJSONObject(j);
                    //传真地址
                    String url = urlObject.getString("url")
                    String sql = "insert into swg_wateroffsync_fax_url(rec_guid,url) values('" + recGuid + "','" + url + "')";
                    int urlRow = eliteBean.update(sql, "dataSource");
                    log.debug("插入传真地址swg_wateroffsync_fax_url表数据：" + urlRow);
                }
                for (int k = 0; k < companyArray.size(); k++) {
                    //传真通知单位对象
                    JSONObject companyObject = companyArray.getJSONObject(k);
                    //传真通知单位
                    String companyName = companyObject.getString("companyname");
                    //传真号码
                    String companyMobile = companyObject.getString("companymobile");

                    String companySql = "insert into swg_wateroffsync_fax_company(rec_guid,companyname,companymobile) values('" + recGuid + "','" + companyName + "','" + companyMobile + "')";
                    int companyRow = eliteBean.update(companySql.toString(), "dataSource");
                    log.debug("插入传真单位swg_wateroffsync_fax_company表数据：" + companyRow);
                }
                // 封装用户json报文
                JSONArray resultArr = new JSONArray();
                for (int i = 0; i < jsonArray.size(); i++) {
                    //封装用户json报文
                    JSONObject jsonObj = jsonArray.getJSONObject(i)
                    //获取停水名单用户编号
                    String userCode = jsonObj.getString("usercode");
                    //获取停水名单手机号码
                    String ani = jsonObj.getString("ani");
                    String waterUserSql = "insert into swg_wateroffsync_user(rec_guid,usercode,ani) values('" + recGuid + "','" + userCode + "','" + ani + "')";
                    int userRow = eliteBean.update(waterUserSql.toString(), "dataSource");
                    log.debug("插入swg_wateroffsync_user表停水用户名单数量：" + userRow)

                    String doSendSMSSQL = '''Insert Into Documentout
                                              (Documentout_Guid,
                                               Doctype,
                                               Status,
                                               Trialcount,
                                               Trialcountlimit,
                                               Documentpath,
                                               Createdby,
                                               Createddate,
                                               Expectedstartdate,
                                               Documentto,
                                               Stringfield1,
                                               Stringfield2,
                                               Sms_Guid,
                                               Ucisid)
                                            Values
                                              (\'''' + UUID.randomUUID().toString().toUpperCase() + '''\',
                                               3,
                                               3,
                                               0,
                                               5,
                                               \'''' + content + '''\',
                                               'SELITE',
                                               Getdate(),
                                               Getdate(),
                                               \'''' + ani + '''\',
                                               '计划停水短信',
                                               \'''' + recGuid + '''\',
                                               \'''' + recGuid + '''\',
                                               \'''' + userCode + '''\')''';
                    int documentOutRow = eliteBean.update(doSendSMSSQL, "dataSource");
                    log.debug("执行到Documentout表数据结果：" + documentOutRow);

                    jsonObj.put("code", 1);
                    resultArr.add(jsonObj);
                }

                long endTime = System.currentTimeMillis();
                long dealTime = endTime - startTime;
                // todo 缺失插入IVR数据表 缺失插入传真表
                //插入IVR数据表
                log.debug("IVR播报-入参：wateroffsmsguid" + waterOffSmsGuid + ",	typeid:" + typeId + ",	content:" + ivrContent + ",	waterontime:" + waterOnTime);
                String ivrAddSql = SMSIVRAdd(eliteBean, waterOffSmsGuid, waterOffSmsName, typeId, ivrContent, waterOnTime, person, phone, "dataSource");
                log.debug("插入IVR表数据：" + ivrAddSql);
                //插入传真表
                /*String faxSql = "";
                switch (syncType){
                    case "add":
                        faxSql = FAXAdd(eliteBean,waterOffSmsGuid,waterOffSmsName,waterOffTime,waterOnTime,faxUrl,company,waterOffOldSmsGuid,"dataSource");
                        break;
                    case "change":
                        faxSql = changeFAX(eliteBean, waterOffOldSmsGuid, waterOffChangeType, waterOffChangeReason, faxUrl);
                        break;
                    case "delay":
                        faxSql =  delayFAX(eliteBean, waterOffOldSmsGuid, delay_time, waterOffChangeReason, faxUrl);
                        break;
                    case "cancel":
                        faxSql = FAXcancel(eliteBean, waterOffSmsGuid, waterOffSmsName, cutOffWater, faxUrl);
                        break;
                }
                log.debug("插入传真表数据：" + faxSql);*/
                resultJson.put("code", "1");
                resultJson.put("msg", "批次号:" + waterOffSmsGuid + " Succ处理成功、调用问题处理时长(毫秒):" + dealTime.toString());
                resultJson.put("data", resultArr);
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            resultJson.put("code", "-2");
            resultJson.put("msg", "Exception:可能是JSON格式问题、连接数据库问题、调用问题处理时长(毫秒):" + (System.currentTimeMillis() - startTime).toString());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "智慧停水[计划]", "apiWaterOffSync", jsonBody.toString(), resultJson.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }

        log.debug("数据接入处理完成返回结果:" + resultJson.toString());
        return resultJson.toString();
    }


    // 动态语音
    public static String SMSIVRAdd(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String typeid, String content, String waterontime, String person, String phone, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("IVR播报-动态语音处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String personphone = person + "	" + phone;
        String reJson = null;
        try {
            //查询现有当前动态语音播报是否存在
            def getSelectSQL = eliteBean.chaxun_sql("select count(*) as count from sysc_template1 where wateroffsmsguid= '" + wateroffsmsguid + "' ", "dataSource");
            def count = 0;
            if (getSelectSQL.size() > 0) {
                count = getSelectSQL.get(0).get("count");
                if (count > 0) {//是否存在
                    def getSelecttemplate_idSQL = eliteBean.chaxun_sql("Select Template_Id As template_id From Sysc_Template1 Where Wateroffsmsguid = '" + wateroffsmsguid + "'", "dataSource");
                    String template_id = "";
                    if (getSelecttemplate_idSQL.size() > 0) {
                        template_id = getSelecttemplate_idSQL.get(0).get("template_id");
                    }

                    String[] abandondata = new String[3];
                    //将之前的批次更新为废弃
                    abandondata[0] = "Delete Sysc_Template1 Where 1 = 1 And Wateroffsmsguid = '" + wateroffsmsguid + "'";
                    abandondata[1] = "Delete Prompt_Content Where 1 = 1 And Prompt_Guid = '" + template_id + "'";
                    abandondata[2] = "Insert Into Wateroffivr_His (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime, Changetime, Changestaff, Changedo) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "',getdate(),'SELITE','删除')";

                    log.debug("IVR播报-当前动态语音已经存在执行果SQL:" + abandondata.toString());
                    def abandondataresult = eliteBean.updateBatch(abandondata, dataSourceID);
                    log.debug("IVR播报-当前动态语音已经存在执行结果SQL结果:" + abandondataresult.toString());
                }
            }

            if (!KHUtil.isNull(content)) {
                String template_id = UUID.randomUUID().toString();
                String[] data = new String[5];

                data[0] = "Delete Sysc_Template1 Where 1 = 1 And Wateroffsmsguid Is Not Null And Waterontime <= Getdate()";
                data[1] = "Insert Into Sysc_Template1 (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "')";
                data[2] = "Insert Into Wateroffivr_His (Template_Id, Template_Type, Template_Desc, Createdate, Wateroffsmsguid, Wateroffsmsname, Waterontime, Changetime, Changestaff, Changedo) Values ('" + template_id + "', '" + typeid + "', '" + content + "', GETDATE(),'" + wateroffsmsguid + "','" + wateroffsmsname + "','" + waterontime + "',getdate(),'SELITE','新增')";
                data[3] = "Insert Into Prompt_Content (Prompt_Guid, Prompt_Matter_Id, Content, Priority, Createdate, Area, Createby, Creategroup, Modifytime, Leading_Official, Area_Type) Values ('" + template_id + "','02C0D6','" + content + "','86876F',getdate(),'" + typeid + "','SELITE','SYSTEM',getdate(),'" + personphone + "',CASE '" + typeid + "' WHEN 'JT0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'NA0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'PD0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'LH0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'BA0001' THEN '74BCB8CD-D886-7B4D-BE0E-AAECE71FA6DE' WHEN 'LG0001' THEN '95ED5385-7379-1041-919A-BDF10A1CB5DC' WHEN 'GM0001' THEN 'ED48B3EA-347F-684F-99A3-9C0BA66B744F' END)";
                data[4] = "Insert Into History_Prompt_Content (Prompt_Guid, Prompt_Matter_Id, Content, Priority, Createdate, Area, Steps, Changestaffid, Changedate, Area_Type) Values ('" + template_id + "','02C0D6','" + content + "','86876F',getdate(),'" + typeid + "','新增','SELITE',getdate(),CASE '" + typeid + "' WHEN 'JT0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'NA0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'PD0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'LH0001' THEN '475AE8F5-8C60-0947-96D6-D4999CE07DF4' WHEN 'BA0001' THEN '74BCB8CD-D886-7B4D-BE0E-AAECE71FA6DE' WHEN 'LG0001' THEN '95ED5385-7379-1041-919A-BDF10A1CB5DC' WHEN 'GM0001' THEN 'ED48B3EA-347F-684F-99A3-9C0BA66B744F' END)";

                log.debug("IVR播报-当前动态语音批次新建SQL:" + data.toString());
                def dataresult = eliteBean.updateBatch(data, dataSourceID);
                log.debug("IVR播报-当前动态语音批次新建结果SQL结果:" + dataresult.toString());
            }

            //调用存储过程处理IVR 停水通知 播报内容
            log.debug("IVR播报-SMS_Link调用存储过程处理停水通知数据...");
            def procedure = "{call Dbo.SMS_Link(?,?)}";
            def inputMap = new String[1];
            inputMap[0] = "SMS_Link";

            log.debug("IVR播报-SMS_Link调用存储过程处理SQL:" + procedure);
            def reSult = eliteBean.executeWithReturn(procedure, inputMap, 'dataSource');
            log.debug("IVR播报-SMS_Link调用存储过程处理返回:" + reSult);

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + "-处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\",\"data\":[]}";


        } catch (JSONException e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + "-处理失败(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真处理
    public static String FAXAdd(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String waterofftime, String waterontime, String cutoffwater, String urlinJson, String companyinJson, String wateroffoldsmsguid) {

        long startTime = System.currentTimeMillis();
        log.debug("传真处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("select count(*) as count from waterOffFaxbatch where 1=1 and status!=2 and wateroffsmsguid= '" + wateroffsmsguid + "' ", "dataSource");
            int count = 0;
            if (getSelectSQL.size() > 0) {
                count = getSelectSQL.get(0).get("count");
                if (count > 0) {//存在则废弃之前的批次
                    String[] abandondata = new String[2];
                    //将还未发送成功的批次更新为废弃
                    abandondata[0] = "update waterOffFaxbatch set status=3,suspenddate=GETDATE() where 1=1 and status!=2 and  wateroffsmsguid=  '" + wateroffsmsguid + "'";
                    //废弃还未同步的传真任务
                    abandondata[1] = "update Kh_Sw_Sendfax set status=2 where 1=1 and status=0 and wateroffsmsguid= '" + wateroffsmsguid + "'";

                    log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                    def abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                    log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                }
            }
            String sms_guid = UUID.randomUUID().toString();

            org.json.JSONArray arrJsonArray = new org.json.JSONArray(companyinJson);
            int arrInt = arrJsonArray.length();
            log.debug("接入List数量:" + arrInt);

            if (arrInt > 0) {
                eliteBean.update("Update Waterofffaxbatch Set Ismain = 0 Where Wateroffsmsguid = '" + wateroffsmsguid + "'", "dataSource");
                int batchresult = eliteBean.update("INSERT INTO waterOffFaxbatch(wateroffsmsguid, wateroffsmsname, waterofftime, waterontime, createdate,sms_guid,status,cutoffwater,fileurl,wateroffoldsmsguid,ismain) VALUES ('" + wateroffsmsguid + "', '" + wateroffsmsname + "',  '" + waterofftime + "','" + waterontime + "',GETDATE(),'" + sms_guid + "',0,'" + cutoffwater + "','" + urlinJson + "','" + wateroffoldsmsguid + "',1)", "dataSource");
                log.debug("当前批次新建结果SQL结果:" + batchresult.toString());
            } else {
                log.debug("当前批次无需发送类型是取消通知");
            }

            org.json.JSONArray resArray = new org.json.JSONArray();
            Map<String, String> dealMap = new HashMap<String, String>();
            Map<String, String> dealMsgMap = new HashMap<String, String>();

            for (int i = 0; i < arrInt; i++) {

                org.json.JSONObject arrSmsJson = arrJsonArray.getJSONObject(i);
                String companyname = KHUtil.GetJV(arrSmsJson, "companyname"); //传真通知单位
                String companymobile = KHUtil.GetJV(arrSmsJson, "companymobile"); //传真号码

                String dealResult = "";
                String dealMessage = "";

                //处理结果字段dealResult 1成功 其他失败S
                if (KHUtil.isNull(companymobile)) {
                    dealMessage = KHUtil.isNullMSG("companymobile", companymobile);
                    endTime = System.currentTimeMillis();
                    log.warn(dealMessage);
                    reJson = "{\"resultcode\":\"3\",\"resultmessage\":\"处理失败(" + dealMessage + "),调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
                    return reJson;
                } else {
                    try {//停水通知传真提前24小时发送，这里需要微调一下，超过晚上9点就不能发了，设置为提前（21:00）发送
                        companymobile = companymobile.replace("-", "");

                        //转换时间获取时分秒
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String str = waterofftime;
                        Date d = formatter.parse(str);
                        SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                        String date = format.format(d);
                        log.debug("获得时分秒date：" + date);

                        String[] data = new String[2];
                        data[0] = "Insert Into Kh_Sw_Sendfax(Rec_Guid,sms_guid,wateroffsmsguid,Subject,Faxnumber,Faxnumberext,Rawfile,Firstpage,Lastpage,Qr,Status,Expectedstartdate) Values(newid(),'" + sms_guid + "','" + wateroffsmsguid + "','" + wateroffsmsname + "', '" + companymobile + "', '', '" + urlinJson + "', '', '', '{}', 0, GETDATE())";
                        data[1] = "update waterOffFaxbatch set count=count+1 where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'";

                        log.debug("当前传真号码执行insert结果SQL:" + data.toString());

                        int[] dataresult = eliteBean.updateBatch(data, "dataSource");
                        log.debug("当前传真号码执行insert结果SQL结果:" + dataresult.toString());

                        dealResult = "1";
                        log.debug("当前传真号码insert执行结果，dataresult:" + dataresult);
                    } catch (Exception e) {
                        dealResult = "0";
                        dealMessage = "当前传真号码insert执行更新结果SQL异常";
                        log.error(dealMessage + ":" + e.getMessage());
                    }
                    log.debug("当前传真号码ID:" + companymobile + " 处理结果Code:" + dealResult + " 处理结果Message:" + dealMessage);
                    dealMap.put(companymobile, dealResult);
                    dealMsgMap.put(companymobile, dealMessage);
                }
            }

            // 将每条处理结果转换为JSONArray
            int j = 0;
            for (Map.Entry<String, String> m : dealMap.entrySet()) {
                org.json.JSONObject resObject = new org.json.JSONObject();
                resObject.put("companymobile", m.getKey());
                resObject.put("code", m.getValue());
                resObject.put("message", dealMsgMap.get(m.getKey()).toString());
                resArray.put(j, resObject);
                j++;
            }

            int statusresult = eliteBean.update("update waterOffFaxbatch set status=1,modifydate=GETDATE() where wateroffsmsguid=  '" + wateroffsmsguid + "' and sms_guid='" + sms_guid + "'", "dataSource");
            log.debug("当前批次同步完成	status更新:" + statusresult.toString());

            //生成处理完成时间
            endTime = System.currentTimeMillis();

            // 包装拼接返回JSONObject
            reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理完成,调用处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":" + resArray.toString() + "}";


        } catch (JSONException e) {
            endTime = System.currentTimeMillis();
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + ",批次名称：" + wateroffsmsname + "处理失败(" + e.getMessage() + "),调用处理时长(毫秒):" + (endTime - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真改期处理
    public static String changeFAX(EliteBean eliteBean, String wateroffsmsguid, String wateroffchangetype, String wateroffchangereason, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真改期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {

                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                // 将批次改为改期
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status       = 5,
                                           Ismain       = 0,
                                           Suspenddate  = Getdate(),
                                           Changetype   = \'''' + wateroffchangetype + '''\',
                                           Changereason = \'''' + wateroffchangereason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -5
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' AS wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' AS urlinJson,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' AS Qr,
                                                 0 AS Status,
                                                 Getdate() AS Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (JSONException e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 改期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真延期处理
    public static String delayFAX(EliteBean eliteBean, String wateroffsmsguid, String wateroffdelaytime, String wateroffdelayreason, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真延期处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {
                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status      = 6,
                                           Ismain       = 0,
                                           Suspenddate = Getdate(),
                                           Delaytime   = \'''' + wateroffdelaytime + '''\',
                                           Delayreason = \'''' + wateroffdelayreason + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -6
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' AS wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' AS urlinJson,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' AS Qr,
                                                 0 AS Status,
                                                 Getdate() AS Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());

                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理完成,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 延期处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }

    // 传真取消处理-4
    public static String FAXcancel(EliteBean eliteBean, String wateroffsmsguid, String wateroffsmsname, String cutoffwater, String urlinJson) {

        long startTime = System.currentTimeMillis();
        log.debug("传真取消处理开始时间:" + startTime);

        String Sms_Guid = UUID.randomUUID().toString();

        String reJson = null;
        try {
            //查询现有当前传真批次是否存在
            List getSelectSQL = eliteBean.chaxun_sql("Select Sms_Guid From Waterofffaxbatch Where Wateroffsmsguid = '" + wateroffsmsguid + "' And Ismain = 1", "dataSource");
            if (getSelectSQL.size() > 0) {
                String old_Sms_Guid = getSelectSQL.get(0).get("Sms_Guid");

                String[] abandondata = new String[4];
                //将还未发送成功的批次更新为废弃
                abandondata[0] = '''Update Waterofffaxbatch
                                       Set Status      = 4,
                                           Ismain       = 0,
                                           Suspenddate = Getdate(),
                                           Canceltime   = Getdate(),
                                           Cancelreason = \'''' + cutoffwater + '''\'
                                     Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                // 废弃还未同步的传真任务
                abandondata[1] = '''Update Kh_Sw_Sendfax
                                           Set Status = -4
                                         Where Status = 0
                                           And Sms_Guid = \'''' + old_Sms_Guid + '''\'''';
                // 新生成主任务
                abandondata[2] = '''Insert Into Waterofffaxbatch
                                          (Wateroffsmsguid,
                                           Wateroffsmsname,
                                           Waterofftime,
                                           Waterontime,
                                           Createdate,
                                           Sms_Guid,
                                           Status,
                                           Cutoffwater,
                                           Fileurl,
                                           Wateroffoldsmsguid, Ismain, Count)
                                          Select Wateroffsmsguid,
                                                 Wateroffsmsname,
                                                 Waterofftime,
                                                 Waterontime,
                                                 Getdate(),
                                                 \'''' + Sms_Guid + '''\',
                                                 1,
                                                 Cutoffwater,
                                                 \'''' + urlinJson + '''\',
                                                 Wateroffoldsmsguid, 1, Count
                                            From Waterofffaxbatch
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\'''';

                abandondata[3] = '''Insert Into Kh_Sw_Sendfax
                                          (Rec_Guid,
                                           Sms_Guid,
                                           Wateroffsmsguid,
                                           Subject,
                                           Faxnumber,
                                           Faxnumberext,
                                           Rawfile,
                                           Firstpage,
                                           Lastpage,
                                           Qr,
                                           Status,
                                           Expectedstartdate)
                                          Select Newid(),* From (Select Distinct
                                                 \'''' + Sms_Guid + '''\' As Sms_Guid,
                                                 \'''' + wateroffsmsguid + '''\' As wateroffsmsguid,
                                                 Subject,
                                                 Faxnumber,
                                                 Faxnumberext,
                                                 \'''' + urlinJson + '''\' As Rawfile,
                                                 Firstpage,
                                                 Lastpage,
                                                 '{}' As Qr,
                                                 0 As Status,
                                                 Getdate() As Expectedstartdate
                                            From Kh_Sw_Sendfax
                                           Where Sms_Guid = \'''' + old_Sms_Guid + '''\') R1''';

                log.debug("当前传真批次已经存在执行结果SQL:" + abandondata.toString());
                int[] abandondataresult = eliteBean.updateBatch(abandondata, "dataSource");
                log.debug("当前传真批次已经存在执行结果SQL结果:" + abandondataresult.toString());


                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 处理完成,当前批次CRM取消成功,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            } else {
                // 包装拼接返回JSONObject
                reJson = "{\"resultcode\":\"1\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理失败,当前批次CRM不存在,调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
            }

        } catch (Exception e) {
            reJson = "{\"resultcode\":\"4\",\"resultmessage\":\"批次号:" + wateroffsmsguid + " 取消处理异常(" + e.getMessage() + "),调用处理时长(毫秒):" + (System.currentTimeMillis() - startTime) + "\"}";
        }

        return reJson;
    }
}
